package com.xuan.config;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.xuan.constants.LoggingConstants.LOGGING_QUEUE;

@Configuration
public class RabbitMQConfig {
    @Autowired
    private ConnectionFactory connectionFactory;
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
    @Bean
    public SimpleRabbitListenerContainerFactory autoAckContainerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setAcknowledgeMode(AcknowledgeMode.AUTO);  // 自动确认
        factory.setMessageConverter(jsonMessageConverter()); // 必须设置
        factory.setPrefetchCount(250);  // 默认预取数量
        return factory;
    }
    // 手动确认模式的容器工厂
    @Bean
    public SimpleRabbitListenerContainerFactory manualAckContainerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);  // 手动确认
        factory.setPrefetchCount(1);  // 每次只处理一条消息
        factory.setMessageConverter(jsonMessageConverter()); // 必须设置
        return factory;
    }
    @Bean
    public Queue loggingQueue() {
        return new Queue(LOGGING_QUEUE, true, false, false);
    }
}
